import { boot } from 'quasar/wrappers';
import axios from 'axios';

import router from '../router/index';

import { LocalStorage } from 'quasar';
import { browserInfo, osInfo } from '../lib/ClientInformation';

// Be careful when using SSR for cross-request state pollution
// due to creating a Singleton instance here;
// If any client changes this (global) instance, it might be a
// good idea to move this instance creation inside of the
// "export default () => {}" function below (which runs individually
// for each client)
let baseURL = '';
if (process.env.SERVER) { // 客户端不执行
  baseURL = 'http://localhost:' + (process.env.HTTP_PORT || process.env.DEV_HTTP_PORT);
}
const axiosLocal = axios.create({ baseURL }); // ssr的preFetch时使用
// const api = axios.create({ baseURL: 'https://api.example.com' })

// 请求拦截器，在请求头中加token
const reqIctCfg = config => {
  if (LocalStorage.getItem('token')) { // 管理端的token
    config.headers.Authorization = LocalStorage.getItem('token');
  }
  if (process.env.CLIENT) {
    const browser = browserInfo()
    config.headers.browser = `${browser.browser} ${browser.ver}`
    config.headers.os = osInfo()
  }

  return config
};
// 请求拦截器错误处理
const reqIctErr = error => {
  return Promise.reject(error);
};

// 响应拦截器，401错误
const resIctCfg = response => {
  if (response.headers.authorization) { // 更新token
    const user = LocalStorage.getItem('user');
    if (response.headers.reauthuid == user.id) { // 用户id对上了再更新jwt
      LocalStorage.set('token', response.headers.authorization);
    }
  }
  return response
};
// 响应拦截错误处理
const resIctErr = error => {
  if (error.response) {
    switch (error.response.status) {
      case 401:
        // 返回 401 清除token信息并跳转到登录页面
        LocalStorage.clear();

        setTimeout(() => {
          router && router.replace({ path: '/' });
        }, 500);

        break
    }
  }
  return Promise.reject(error)// 返回接口返回的错误信息
};

const axiosEle = axios.create({ baseURL });

axios.interceptors.request.use(reqIctCfg, reqIctErr);
axios.interceptors.response.use(resIctCfg, resIctErr);

const axiosInstance = axios.create();

export default boot(({ app }) => {
  // for use inside Vue files (Options API) through this.$axios and this.$api

  app.config.globalProperties.$axios = axios;
  // ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
  //       so you won't necessarily have to import axios in each vue file

  // app.config.globalProperties.$api = api
  // ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
  //       so you can easily perform requests against your app's API
})

export { axiosInstance, axiosLocal, axiosEle }
